{% extends 'assets/base.html' %}
{% load static %}

{% block title %}工作流设计器{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/jsplumb@2.15.6/dist/css/jsplumbtoolkit-defaults.css" rel="stylesheet">
<style>
.workflow-designer {
    height: 80vh;
    border: 1px solid #ddd;
    position: relative;
    background: #f8f9fa;
    overflow: hidden;
}

.designer-toolbar {
    background: white;
    border-bottom: 1px solid #ddd;
    padding: 10px;
    display: flex;
    gap: 10px;
    align-items: center;
}

.designer-canvas {
    height: calc(100% - 60px);
    position: relative;
    overflow: auto;
}

.step-palette {
    position: absolute;
    left: 10px;
    top: 10px;
    width: 200px;
    background: white;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 10px;
    z-index: 1000;
}

.step-template {
    display: flex;
    align-items: center;
    padding: 8px;
    margin: 5px 0;
    background: #f8f9fa;
    border: 1px solid #ddd;
    border-radius: 3px;
    cursor: grab;
    transition: all 0.2s;
}

.step-template:hover {
    background: #e9ecef;
    transform: translateY(-1px);
}

.step-template i {
    margin-right: 8px;
    width: 16px;
}

.workflow-step {
    position: absolute;
    width: 120px;
    height: 80px;
    background: white;
    border: 2px solid #007bff;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: move;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: all 0.2s;
}

.workflow-step:hover {
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
    transform: translateY(-1px);
}

.workflow-step.selected {
    border-color: #28a745;
    box-shadow: 0 0 0 3px rgba(40, 167, 69, 0.25);
}

.workflow-step.manual {
    border-color: #007bff;
}

.workflow-step.auto {
    border-color: #28a745;
}

.workflow-step.condition {
    border-color: #ffc107;
    border-radius: 50%;
}

.workflow-step.parallel {
    border-color: #6f42c1;
}

.workflow-step.notification {
    border-color: #17a2b8;
}

.step-icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.step-name {
    font-size: 12px;
    text-align: center;
    font-weight: bold;
}

.properties-panel {
    position: absolute;
    right: 10px;
    top: 10px;
    width: 300px;
    background: white;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 15px;
    z-index: 1000;
    max-height: 70vh;
    overflow-y: auto;
}

.properties-panel h6 {
    margin-bottom: 15px;
    color: #495057;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    font-weight: 600;
    margin-bottom: 5px;
    display: block;
}

.connection-line {
    stroke: #007bff;
    stroke-width: 2;
    fill: none;
    marker-end: url(#arrowhead);
}

.minimap {
    position: absolute;
    bottom: 10px;
    right: 10px;
    width: 200px;
    height: 150px;
    background: white;
    border: 1px solid #ddd;
    border-radius: 5px;
    z-index: 1000;
}

.zoom-controls {
    position: absolute;
    bottom: 10px;
    left: 10px;
    display: flex;
    flex-direction: column;
    gap: 5px;
    z-index: 1000;
}

.zoom-btn {
    width: 40px;
    height: 40px;
    border: none;
    background: white;
    border: 1px solid #ddd;
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}

.zoom-btn:hover {
    background: #f8f9fa;
}

.workflow-json {
    background: #f8f9fa;
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 10px;
    font-family: monospace;
    font-size: 12px;
    max-height: 300px;
    overflow-y: auto;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-project-diagram"></i> 工作流设计器</h2>
        <div class="btn-group">
            <button type="button" class="btn btn-outline-secondary" onclick="clearCanvas()">
                <i class="fas fa-eraser"></i> 清空
            </button>
            <button type="button" class="btn btn-outline-info" onclick="previewWorkflow()">
                <i class="fas fa-eye"></i> 预览
            </button>
            <button type="button" class="btn btn-success" onclick="saveWorkflow()">
                <i class="fas fa-save"></i> 保存
            </button>
        </div>
    </div>

    <!-- 设计器工具栏 -->
    <div class="designer-toolbar">
        <button type="button" class="btn btn-sm btn-outline-primary" onclick="addStep('manual')">
            <i class="fas fa-user"></i> 人工审批
        </button>
        <button type="button" class="btn btn-sm btn-outline-success" onclick="addStep('auto')">
            <i class="fas fa-cog"></i> 自动处理
        </button>
        <button type="button" class="btn btn-sm btn-outline-warning" onclick="addStep('condition')">
            <i class="fas fa-question-circle"></i> 条件判断
        </button>
        <button type="button" class="btn btn-sm btn-outline-info" onclick="addStep('notification')">
            <i class="fas fa-bell"></i> 发送通知
        </button>
        <button type="button" class="btn btn-sm btn-outline-purple" onclick="addStep('parallel')">
            <i class="fas fa-code-branch"></i> 并行处理
        </button>
        <div class="ms-auto">
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="toggleGrid()">
                <i class="fas fa-th"></i> 网格
            </button>
            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="autoLayout()">
                <i class="fas fa-magic"></i> 自动布局
            </button>
        </div>
    </div>

    <!-- 设计器画布 -->
    <div class="workflow-designer">
        <div class="designer-canvas" id="designerCanvas">
            <!-- 步骤调色板 -->
            <div class="step-palette">
                <h6><i class="fas fa-palette"></i> 步骤类型</h6>
                <div class="step-template" draggable="true" data-step-type="manual">
                    <i class="fas fa-user text-primary"></i>
                    <span>人工审批</span>
                </div>
                <div class="step-template" draggable="true" data-step-type="auto">
                    <i class="fas fa-cog text-success"></i>
                    <span>自动处理</span>
                </div>
                <div class="step-template" draggable="true" data-step-type="condition">
                    <i class="fas fa-question-circle text-warning"></i>
                    <span>条件判断</span>
                </div>
                <div class="step-template" draggable="true" data-step-type="notification">
                    <i class="fas fa-bell text-info"></i>
                    <span>发送通知</span>
                </div>
                <div class="step-template" draggable="true" data-step-type="parallel">
                    <i class="fas fa-code-branch text-purple"></i>
                    <span>并行处理</span>
                </div>
            </div>

            <!-- 属性面板 -->
            <div class="properties-panel" id="propertiesPanel" style="display: none;">
                <h6><i class="fas fa-cogs"></i> 步骤属性</h6>
                <div id="stepProperties">
                    <!-- 动态生成的属性表单 -->
                </div>
            </div>

            <!-- 缩放控制 -->
            <div class="zoom-controls">
                <button class="zoom-btn" onclick="zoomIn()">
                    <i class="fas fa-plus"></i>
                </button>
                <button class="zoom-btn" onclick="zoomOut()">
                    <i class="fas fa-minus"></i>
                </button>
                <button class="zoom-btn" onclick="resetZoom()">
                    <i class="fas fa-expand-arrows-alt"></i>
                </button>
            </div>

            <!-- 小地图 -->
            <div class="minimap" id="minimap">
                <canvas width="200" height="150"></canvas>
            </div>
        </div>
    </div>
</div><
!-- 保存工作流模态框 -->
<div class="modal fade" id="saveWorkflowModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">保存工作流模板</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="saveWorkflowForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>模板名称</label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>模板类型</label>
                                <select class="form-select" name="template_type" required>
                                    <option value="">请选择类型</option>
                                    <option value="asset_transfer">资产调拨</option>
                                    <option value="asset_borrow">资产借用</option>
                                    <option value="maintenance_request">维修申请</option>
                                    <option value="asset_scrap">资产报废</option>
                                    <option value="inventory_plan">盘点计划</option>
                                    <option value="custom">自定义</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>模板描述</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label>工作流定义 (JSON)</label>
                        <div class="workflow-json" id="workflowJson">
                            <!-- 工作流JSON将在这里显示 -->
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-success" onclick="submitSaveWorkflow()">保存模板</button>
            </div>
        </div>
    </div>
</div>

<!-- 预览工作流模态框 -->
<div class="modal fade" id="previewWorkflowModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">工作流预览</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>流程图</h6>
                        <div id="previewCanvas" style="height: 400px; border: 1px solid #ddd; background: #f8f9fa;">
                            <!-- 预览画布 -->
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6>流程定义</h6>
                        <div class="workflow-json" id="previewJson">
                            <!-- 预览JSON -->
                        </div>
                        <h6 class="mt-3">步骤列表</h6>
                        <div id="stepsList">
                            <!-- 步骤列表 -->
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="validateWorkflow()">验证流程</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/jsplumb@2.15.6/dist/js/jsplumb.min.js"></script>
<script>
// 全局变量
let jsPlumbInstance;
let currentStepId = 1;
let selectedStep = null;
let workflowSteps = {};
let workflowConnections = [];
let zoomLevel = 1;
let gridEnabled = true;

// 初始化设计器
document.addEventListener('DOMContentLoaded', function() {
    initializeDesigner();
    setupEventListeners();
});

function initializeDesigner() {
    // 初始化jsPlumb
    jsPlumbInstance = jsPlumb.getInstance({
        Container: 'designerCanvas',
        Connector: ['Bezier', { curviness: 50 }],
        Anchors: ['Top', 'Bottom', 'Left', 'Right'],
        Endpoint: ['Dot', { radius: 5 }],
        EndpointStyle: { fill: '#007bff' },
        PaintStyle: { stroke: '#007bff', strokeWidth: 2 },
        HoverPaintStyle: { stroke: '#28a745', strokeWidth: 3 },
        ConnectionOverlays: [
            ['Arrow', { location: 1, width: 10, length: 10 }]
        ]
    });

    // 设置连接事件
    jsPlumbInstance.bind('connection', function(info) {
        onConnectionCreated(info);
    });

    jsPlumbInstance.bind('connectionDetached', function(info) {
        onConnectionDetached(info);
    });

    // 启用拖拽
    jsPlumbInstance.draggable(jsPlumbInstance.getSelector('.workflow-step'), {
        grid: [20, 20],
        containment: 'parent'
    });
}

function setupEventListeners() {
    const canvas = document.getElementById('designerCanvas');
    
    // 画布点击事件
    canvas.addEventListener('click', function(e) {
        if (e.target === canvas) {
            deselectAllSteps();
        }
    });

    // 拖拽事件
    const stepTemplates = document.querySelectorAll('.step-template');
    stepTemplates.forEach(template => {
        template.addEventListener('dragstart', function(e) {
            e.dataTransfer.setData('text/plain', this.dataset.stepType);
        });
    });

    canvas.addEventListener('dragover', function(e) {
        e.preventDefault();
    });

    canvas.addEventListener('drop', function(e) {
        e.preventDefault();
        const stepType = e.dataTransfer.getData('text/plain');
        const rect = canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        if (stepType) {
            createStep(stepType, x, y);
        }
    });

    // 键盘事件
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Delete' && selectedStep) {
            deleteStep(selectedStep);
        }
    });
}

function addStep(stepType) {
    const canvas = document.getElementById('designerCanvas');
    const rect = canvas.getBoundingClientRect();
    const x = Math.random() * (rect.width - 200) + 100;
    const y = Math.random() * (rect.height - 200) + 100;
    
    createStep(stepType, x, y);
}

function createStep(stepType, x, y) {
    const stepId = `step_${currentStepId++}`;
    const stepName = getStepTypeName(stepType);
    const stepIcon = getStepTypeIcon(stepType);
    
    // 创建步骤元素
    const stepElement = document.createElement('div');
    stepElement.className = `workflow-step ${stepType}`;
    stepElement.id = stepId;
    stepElement.style.left = `${x}px`;
    stepElement.style.top = `${y}px`;
    
    stepElement.innerHTML = `
        <div class="step-icon">
            <i class="${stepIcon}"></i>
        </div>
        <div class="step-name">${stepName}</div>
    `;
    
    // 添加到画布
    document.getElementById('designerCanvas').appendChild(stepElement);
    
    // 添加点击事件
    stepElement.addEventListener('click', function(e) {
        e.stopPropagation();
        selectStep(stepId);
    });
    
    // 添加双击事件
    stepElement.addEventListener('dblclick', function(e) {
        e.stopPropagation();
        editStepProperties(stepId);
    });
    
    // 使元素可拖拽和可连接
    jsPlumbInstance.draggable(stepElement, {
        grid: gridEnabled ? [20, 20] : [1, 1],
        containment: 'parent'
    });
    
    jsPlumbInstance.makeSource(stepElement, {
        filter: '.step-icon',
        anchor: 'Continuous',
        connectorStyle: { stroke: '#007bff', strokeWidth: 2 },
        connectionType: 'basic'
    });
    
    jsPlumbInstance.makeTarget(stepElement, {
        dropOptions: { hoverClass: 'dragHover' },
        anchor: 'Continuous'
    });
    
    // 保存步骤数据
    workflowSteps[stepId] = {
        id: stepId,
        name: stepName,
        type: stepType,
        position: { x: x, y: y },
        config: getDefaultStepConfig(stepType)
    };
    
    // 选中新创建的步骤
    selectStep(stepId);
}

function getStepTypeName(stepType) {
    const names = {
        'manual': '人工审批',
        'auto': '自动处理',
        'condition': '条件判断',
        'notification': '发送通知',
        'parallel': '并行处理',
        'timer': '定时器',
        'script': '脚本执行'
    };
    return names[stepType] || stepType;
}

function getStepTypeIcon(stepType) {
    const icons = {
        'manual': 'fas fa-user',
        'auto': 'fas fa-cog',
        'condition': 'fas fa-question-circle',
        'notification': 'fas fa-bell',
        'parallel': 'fas fa-code-branch',
        'timer': 'fas fa-clock',
        'script': 'fas fa-code'
    };
    return icons[stepType] || 'fas fa-circle';
}

function getDefaultStepConfig(stepType) {
    const configs = {
        'manual': {
            assignee: { type: 'user', user_id: null },
            timeout: 24,
            reject_terminates_workflow: true
        },
        'auto': {
            action: { type: 'update_object', updates: {} }
        },
        'condition': {
            condition: { type: 'simple', field: '', operator: 'equals', value: '' },
            on_true: [],
            on_false: []
        },
        'notification': {
            notification: {
                recipients: { creator: true },
                title: '工作流通知',
                message: '您有一个新的工作流通知',
                channels: ['system']
            }
        },
        'parallel': {
            parallel_steps: []
        }
    };
    return configs[stepType] || {};
}

function selectStep(stepId) {
    // 取消之前的选择
    deselectAllSteps();
    
    // 选中当前步骤
    const stepElement = document.getElementById(stepId);
    if (stepElement) {
        stepElement.classList.add('selected');
        selectedStep = stepId;
        
        // 显示属性面板
        showStepProperties(stepId);
    }
}

function deselectAllSteps() {
    document.querySelectorAll('.workflow-step.selected').forEach(step => {
        step.classList.remove('selected');
    });
    selectedStep = null;
    hideStepProperties();
}

function deleteStep(stepId) {
    if (confirm('确定要删除这个步骤吗？')) {
        // 删除连接
        jsPlumbInstance.removeAllEndpoints(stepId);
        
        // 删除元素
        const stepElement = document.getElementById(stepId);
        if (stepElement) {
            stepElement.remove();
        }
        
        // 删除数据
        delete workflowSteps[stepId];
        
        // 清除选择
        if (selectedStep === stepId) {
            selectedStep = null;
            hideStepProperties();
        }
    }
}

function showStepProperties(stepId) {
    const step = workflowSteps[stepId];
    if (!step) return;
    
    const panel = document.getElementById('propertiesPanel');
    const container = document.getElementById('stepProperties');
    
    // 生成属性表单
    container.innerHTML = generateStepPropertiesForm(step);
    
    // 显示面板
    panel.style.display = 'block';
}

function hideStepProperties() {
    document.getElementById('propertiesPanel').style.display = 'none';
}

function generateStepPropertiesForm(step) {
    let html = `
        <div class="form-group">
            <label>步骤名称</label>
            <input type="text" class="form-control" value="${step.name}" 
                   onchange="updateStepProperty('${step.id}', 'name', this.value)">
        </div>
        <div class="form-group">
            <label>步骤类型</label>
            <input type="text" class="form-control" value="${step.type}" readonly>
        </div>
    `;
    
    // 根据步骤类型生成特定配置
    if (step.type === 'manual') {
        html += `
            <div class="form-group">
                <label>分配类型</label>
                <select class="form-select" onchange="updateStepConfig('${step.id}', 'assignee.type', this.value)">
                    <option value="user" ${step.config.assignee?.type === 'user' ? 'selected' : ''}>指定用户</option>
                    <option value="role" ${step.config.assignee?.type === 'role' ? 'selected' : ''}>角色</option>
                    <option value="group" ${step.config.assignee?.type === 'group' ? 'selected' : ''}>用户组</option>
                </select>
            </div>
            <div class="form-group">
                <label>超时时间(小时)</label>
                <input type="number" class="form-control" value="${step.config.timeout || 24}" 
                       onchange="updateStepConfig('${step.id}', 'timeout', parseInt(this.value))">
            </div>
        `;
    } else if (step.type === 'condition') {
        html += `
            <div class="form-group">
                <label>条件字段</label>
                <input type="text" class="form-control" value="${step.config.condition?.field || ''}" 
                       onchange="updateStepConfig('${step.id}', 'condition.field', this.value)">
            </div>
            <div class="form-group">
                <label>操作符</label>
                <select class="form-select" onchange="updateStepConfig('${step.id}', 'condition.operator', this.value)">
                    <option value="equals" ${step.config.condition?.operator === 'equals' ? 'selected' : ''}>等于</option>
                    <option value="not_equals" ${step.config.condition?.operator === 'not_equals' ? 'selected' : ''}>不等于</option>
                    <option value="greater_than" ${step.config.condition?.operator === 'greater_than' ? 'selected' : ''}>大于</option>
                    <option value="less_than" ${step.config.condition?.operator === 'less_than' ? 'selected' : ''}>小于</option>
                </select>
            </div>
            <div class="form-group">
                <label>比较值</label>
                <input type="text" class="form-control" value="${step.config.condition?.value || ''}" 
                       onchange="updateStepConfig('${step.id}', 'condition.value', this.value)">
            </div>
        `;
    } else if (step.type === 'notification') {
        html += `
            <div class="form-group">
                <label>通知标题</label>
                <input type="text" class="form-control" value="${step.config.notification?.title || ''}" 
                       onchange="updateStepConfig('${step.id}', 'notification.title', this.value)">
            </div>
            <div class="form-group">
                <label>通知内容</label>
                <textarea class="form-control" rows="3" 
                          onchange="updateStepConfig('${step.id}', 'notification.message', this.value)">${step.config.notification?.message || ''}</textarea>
            </div>
        `;
    }
    
    return html;
}

function updateStepProperty(stepId, property, value) {
    if (workflowSteps[stepId]) {
        workflowSteps[stepId][property] = value;
        
        // 更新显示
        if (property === 'name') {
            const stepElement = document.getElementById(stepId);
            const nameElement = stepElement.querySelector('.step-name');
            if (nameElement) {
                nameElement.textContent = value;
            }
        }
    }
}

function updateStepConfig(stepId, configPath, value) {
    if (workflowSteps[stepId]) {
        const pathParts = configPath.split('.');
        let config = workflowSteps[stepId].config;
        
        // 导航到正确的配置位置
        for (let i = 0; i < pathParts.length - 1; i++) {
            if (!config[pathParts[i]]) {
                config[pathParts[i]] = {};
            }
            config = config[pathParts[i]];
        }
        
        // 设置值
        config[pathParts[pathParts.length - 1]] = value;
    }
}

function onConnectionCreated(info) {
    const sourceId = info.source.id;
    const targetId = info.target.id;
    
    workflowConnections.push({
        source: sourceId,
        target: targetId
    });
}

function onConnectionDetached(info) {
    const sourceId = info.source.id;
    const targetId = info.target.id;
    
    workflowConnections = workflowConnections.filter(conn => 
        !(conn.source === sourceId && conn.target === targetId)
    );
}

function clearCanvas() {
    if (confirm('确定要清空画布吗？所有步骤和连接都将被删除。')) {
        // 清除所有连接
        jsPlumbInstance.deleteEveryConnection();
        
        // 清除所有步骤
        document.querySelectorAll('.workflow-step').forEach(step => {
            step.remove();
        });
        
        // 重置数据
        workflowSteps = {};
        workflowConnections = [];
        currentStepId = 1;
        selectedStep = null;
        
        hideStepProperties();
    }
}

function generateWorkflowDefinition() {
    const steps = [];
    const stepIds = Object.keys(workflowSteps);
    
    // 生成步骤定义
    stepIds.forEach(stepId => {
        const step = workflowSteps[stepId];
        const stepDef = {
            id: stepId,
            name: step.name,
            type: step.type,
            ...step.config
        };
        
        // 添加依赖关系
        const dependencies = workflowConnections
            .filter(conn => conn.target === stepId)
            .map(conn => conn.source);
        
        if (dependencies.length > 0) {
            stepDef.depends_on = dependencies;
        }
        
        steps.push(stepDef);
    });
    
    return {
        steps: steps,
        completion_actions: {},
        metadata: {
            created_at: new Date().toISOString(),
            version: '1.0'
        }
    };
}

function previewWorkflow() {
    const workflowDef = generateWorkflowDefinition();
    
    // 显示JSON
    document.getElementById('previewJson').textContent = JSON.stringify(workflowDef, null, 2);
    
    // 生成步骤列表
    const stepsList = document.getElementById('stepsList');
    stepsList.innerHTML = '';
    
    workflowDef.steps.forEach(step => {
        const stepItem = document.createElement('div');
        stepItem.className = 'mb-2 p-2 border rounded';
        stepItem.innerHTML = `
            <strong>${step.name}</strong> (${step.type})
            ${step.depends_on ? `<br><small class="text-muted">依赖: ${step.depends_on.join(', ')}</small>` : ''}
        `;
        stepsList.appendChild(stepItem);
    });
    
    // 显示模态框
    new bootstrap.Modal(document.getElementById('previewWorkflowModal')).show();
}

function saveWorkflow() {
    const workflowDef = generateWorkflowDefinition();
    
    // 显示JSON
    document.getElementById('workflowJson').textContent = JSON.stringify(workflowDef, null, 2);
    
    // 显示保存模态框
    new bootstrap.Modal(document.getElementById('saveWorkflowModal')).show();
}

function submitSaveWorkflow() {
    const form = document.getElementById('saveWorkflowForm');
    const formData = new FormData(form);
    const workflowDef = generateWorkflowDefinition();
    
    const data = {
        name: formData.get('name'),
        template_type: formData.get('template_type'),
        description: formData.get('description'),
        workflow_definition: workflowDef
    };
    
    fetch('/assets/workflow/templates/create/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken')
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('工作流模板保存成功！');
            bootstrap.Modal.getInstance(document.getElementById('saveWorkflowModal')).hide();
        } else {
            alert('保存失败: ' + data.message);
        }
    })
    .catch(error => {
        alert('保存失败: ' + error.message);
    });
}

function validateWorkflow() {
    const workflowDef = generateWorkflowDefinition();
    const errors = [];
    
    // 验证步骤
    if (workflowDef.steps.length === 0) {
        errors.push('工作流至少需要一个步骤');
    }
    
    // 验证连接
    const stepIds = workflowDef.steps.map(s => s.id);
    workflowDef.steps.forEach(step => {
        if (step.depends_on) {
            step.depends_on.forEach(depId => {
                if (!stepIds.includes(depId)) {
                    errors.push(`步骤 ${step.name} 依赖的步骤 ${depId} 不存在`);
                }
            });
        }
    });
    
    // 检查循环依赖
    if (hasCyclicDependency(workflowDef.steps)) {
        errors.push('工作流存在循环依赖');
    }
    
    if (errors.length === 0) {
        alert('工作流验证通过！');
    } else {
        alert('工作流验证失败:\n' + errors.join('\n'));
    }
}

function hasCyclicDependency(steps) {
    // 简单的循环依赖检测
    const visited = new Set();
    const recursionStack = new Set();
    
    function dfs(stepId) {
        if (recursionStack.has(stepId)) {
            return true; // 发现循环
        }
        if (visited.has(stepId)) {
            return false;
        }
        
        visited.add(stepId);
        recursionStack.add(stepId);
        
        const step = steps.find(s => s.id === stepId);
        if (step && step.depends_on) {
            for (const depId of step.depends_on) {
                if (dfs(depId)) {
                    return true;
                }
            }
        }
        
        recursionStack.delete(stepId);
        return false;
    }
    
    for (const step of steps) {
        if (dfs(step.id)) {
            return true;
        }
    }
    
    return false;
}

// 缩放和布局功能
function zoomIn() {
    zoomLevel = Math.min(zoomLevel * 1.2, 3);
    applyZoom();
}

function zoomOut() {
    zoomLevel = Math.max(zoomLevel / 1.2, 0.3);
    applyZoom();
}

function resetZoom() {
    zoomLevel = 1;
    applyZoom();
}

function applyZoom() {
    const canvas = document.getElementById('designerCanvas');
    canvas.style.transform = `scale(${zoomLevel})`;
    canvas.style.transformOrigin = 'top left';
}

function toggleGrid() {
    gridEnabled = !gridEnabled;
    // 更新所有步骤的拖拽网格
    document.querySelectorAll('.workflow-step').forEach(step => {
        jsPlumbInstance.draggable(step, {
            grid: gridEnabled ? [20, 20] : [1, 1],
            containment: 'parent'
        });
    });
}

function autoLayout() {
    // 简单的自动布局算法
    const stepIds = Object.keys(workflowSteps);
    const cols = Math.ceil(Math.sqrt(stepIds.length));
    const stepWidth = 140;
    const stepHeight = 100;
    
    stepIds.forEach((stepId, index) => {
        const row = Math.floor(index / cols);
        const col = index % cols;
        const x = col * stepWidth + 50;
        const y = row * stepHeight + 50;
        
        const stepElement = document.getElementById(stepId);
        if (stepElement) {
            stepElement.style.left = `${x}px`;
            stepElement.style.top = `${y}px`;
            
            // 更新数据
            workflowSteps[stepId].position = { x, y };
        }
    });
    
    // 重绘连接
    jsPlumbInstance.repaintEverything();
}

// 工具函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
{% endblock %}